﻿//---------------------------------------------------------------------
// Copyright (c) 2007 Digerati Technologies, LLC.  All Rights Reserved.
//
// Release under the Microsoft Public License (Ms-PL).
//---------------------------------------------------------------------

using System.Diagnostics;

namespace DigeratiTech.NDiagnostics
{
    /// <summary>
    /// This <see cref="DiagnosticTask"/> verifies that the specified process is running.
    /// </summary>
    public class ProcessRunningTask : DiagnosticTask
    {
        #region Properties...

        /// <summary>
        /// Gets or sets the name of the process to check for.
        /// </summary>
        /// <value>The name of the process to check for.</value>
        public string ProcessName { get; set; }

        /// <summary>
        /// Gets or sets the process description.
        /// </summary>
        /// <value>The process description.</value>
        public string ProcessDescription { get; set; }

        #endregion

        #region Constructors...

        /// <summary>
        /// Initializes a new instance of the <see cref="ProcessRunningTask"/> class.
        /// </summary>
        /// <param name="group">The <see cref="TaskGroup"/> this task belongs to.</param>
        /// <param name="name">The task name.</param>
        /// <param name="processName">The name of the process to check for.</param>
        /// <param name="processDescription">The process description.</param>
        public ProcessRunningTask(TaskGroup group, string name, string processName, string processDescription)
        {
            taskGroup = group;
            Name = name;
            ProcessName = processName;
            ProcessDescription = processDescription;
            Status = TaskStatus.NotRun;
        }

        #endregion

        #region Methods...

        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the task is successful; otherwise, <c>false</c>.
        /// </returns>
        public override bool Execute()
        {
            Status = TaskStatus.Completed;
            Message = string.Empty;

            if (Process.GetProcessesByName(ProcessName).Length == 0)
            {
                Status = TaskStatus.Error;
                Message += ((Message.Length > 0) ? "\n" : "") + string.Format("The process '{0}' ({1}) is not running.", ProcessDescription, ProcessName);
            }

            return (Message.Length == 0);
        }

        #endregion
    }
}
